﻿using GuanQL.Core;
using GuanQL.Core.Domain.Accounts;
using GuanQL.Core.Stores;
using GuanQL.Service.Medias;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
using ZhongJia.Core;
using ZhongJia.Core.Caching;
using ZhongJia.Core.Utility;
namespace GuanQL.Service.Accounts
{
    public class AccountService : IService
    {
        private readonly PictureService _pictureService;
        private readonly GQLDbContext _dbContext;
        private readonly IWebContext _webContext;
        private readonly ICacheClient _cacheClient;
        private const string User_Oper_Time = "User_{0}_Oper_Time";

        public AccountService(
            ICacheClient cacheClient,
            PictureService pictureService,
            GQLDbContext dbContext,
            IWebContext webContext)
        {
            _cacheClient = cacheClient;
            _pictureService = pictureService;
            _webContext = webContext;
            _dbContext = dbContext;
        }

        public async Task<User> FindByUserId(Guid userId)
        {
            return await _dbContext.Set<User>().Include(u => u.Avatar)
                .FirstOrDefaultAsync(u => u.Id == userId && u.TenantId == _webContext.TenantId);
        }

        public async Task LogUserOperTime()
        {
            if (!_webContext.IsLogin)
                return;

            await _cacheClient.GetOrCreate(string.Format(User_Oper_Time, _webContext.CurrentUser.Id), async () =>
            {
                var user = await FindByUserId(_webContext.CurrentUser.Id);
                user.LastestOperTime = SystemClock.Now;
                await _dbContext.SaveChangesAsync();
                return true;
            }, TimeSpan.FromMinutes(5));
        }
    }
}
